package org.dalmatian.common.tenant.manager;


import org.dalmatian.common.core.constants.GlobalConstants;
import org.dalmatian.common.core.utils.StringUtils;
import org.dalmatian.common.redis.cache.Cache;
import org.dalmatian.common.redis.cache.RedissonSolonCache;
import org.dalmatian.common.redis.manager.CaffeineCacheDecorator;
import org.dalmatian.common.redis.manager.PlusSpringCacheManager;
import org.dalmatian.common.tenant.helper.TenantHelper;
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zc
 */
@Slf4j
public class TenantCacheManager extends PlusSpringCacheManager {

    @Override
    public Cache getCache(String name) {
        if (InterceptorIgnoreHelper.willIgnoreTenantLine("")) {
            return super.getCache(name);
        }
        if (StringUtils.contains(name, GlobalConstants.GLOBAL_REDIS_KEY)) {
            return super.getCache(name);
        }
        String tenantId = TenantHelper.getTenantId();
        if (StringUtils.isBlank(tenantId)) {
            log.error("无法获取有效的租户id -> Null");
        }
        if (StringUtils.startsWith(name, tenantId)) {
            // 如果存在则直接返回
            return super.getCache(name);
        }
        return  new CaffeineCacheDecorator(new RedissonSolonCache(tenantId+":"+name), name);
    }

}
